package topsun.rms.utility;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public abstract class WriteJsonUtil 
{
	/**
	 * 将对象转换成JSON字符串，并响应回前台
	 * 
	 * @param object
	 * 			       需要转换的对象
	 * @param includesProperties
	 *            需要转换的属性
	 * @param excludesProperties
	 *            不需要转换的属性
	 * @param request
	 * 
	 * @param response
	 */
	public static void writeJsonByFilter(Object object, String[] includesProperties, String[] excludesProperties, HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			FastjsonFilter filter = new FastjsonFilter();
			if (excludesProperties != null && excludesProperties.length > 0)
			{
				filter.getExcludes().addAll(Arrays.<String> asList(excludesProperties));
			}
			if (includesProperties != null && includesProperties.length > 0)
			{
				filter.getIncludes().addAll(Arrays.<String> asList(includesProperties));
			}
			
			String retJson;
			String User_Agent = request.getHeader("User-Agent");
			if (StringUtils.indexOf(User_Agent, "MSIE 6") > -1) 
			{
				retJson = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat, 
						SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.BrowserCompatible);
			} else 
			{
				retJson = JSON.toJSONString(object, filter, SerializerFeature.WriteDateUseDateFormat, 
						SerializerFeature.DisableCircularReferenceDetect);
			}
			response.setContentType("text/html;charset=utf-8");
			System.out.println(retJson);
			response.getWriter().write(retJson);
			response.getWriter().flush();
			response.getWriter().close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}
